package com.link.base.base.knowledge.controller;

import com.link.base.user.model.CoreUser;
import com.link.base.base.common.model.Attachment;
import com.link.base.base.common.service.AttachmentService;
import com.link.base.base.knowledge.model.Knowledge;
import com.link.base.base.knowledge.service.KnowledgeService;
import com.link.base.base.orgnization.model.Orgnization;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.query.Sorter;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.RedisUtil;
import com.link.core.util.UserUtil;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author qiqian.he
 * @comments 知识库处理
 */
@Controller
@RequestMapping("/link/knowledge")
public class KnowledgeController extends BasicController<Knowledge> {

    @Resource
    private KnowledgeService knowledgeService;
    @Resource
    private KeyGenerateService keyGenerateService;
    @Resource
    private AttachmentService attachmentService;

    @Override
    public BasicService<Knowledge> getBasicService() throws Exception {
        return knowledgeService;
    }

    @Override
    @RequestMapping(value = "/preDefaultValue", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Map<String, Object> preDefaultValue(@JsonParam Knowledge entity, HttpSession session, HttpServletRequest request,
                                               HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Knowledge newEntity = new Knowledge();
            newEntity.setId(keyGenerateService.keyGenerate());
            newEntity.setAuthor(UserUtil.getUser().getFirstName());
            result.put("success", true);
            result.put("result", newEntity);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @Override
    @RequestMapping(value = "/upsert")
    @ResponseBody
    public Map<String, Object> upsert(@JsonParam Knowledge entity, HttpSession session,
                                      HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            beforUpsert(entity, request);
            knowledgeService.upsert(entity);
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> myfiles = multipartRequest.getFiles("uploadAttachment");
            Attachment attachment = null;
            for (MultipartFile mFile : myfiles) {
                if (mFile == null) {
                    throw new ServiceException("PUBLIC-013");
                }
                attachment = new Attachment();
                attachment.setHeadId(entity.getId());
                attachment.setModuleType("Knowledge");
                // 插入附件表
                // 附件上传
                attachmentService.upload(mFile, attachment);
                //向附件表插入附件基础信息
                attachmentService.insert(attachment);
            }
            Knowledge newEntry = knowledgeService.queryById(entity);
            result.put("newRow", newEntry);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 查询一条记录
     */
    @Override
    @RequestMapping(value = "/queryById")
    @ResponseBody
    public Map<String, Object> queryById(@JsonParam Knowledge entity, HttpSession session,
                                         HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Knowledge record;
            Knowledge know = knowledgeService.queryCorpById(entity);
            if (know != null) {
                CoreUser user = UserUtil.getUser();
                if (user != null && user.getCorpid().equals(know.getCorpid())) {
                    record = getBasicService().queryById(entity);
                    // 获取点赞量、浏览量等等缓存数据
                    knowledgeService.setStatisticsData(record, user.getId());
                } else {
                    String flag = "Y";
                    if (flag.equals(know.getPublicTag())) {
                        record = getBasicService().queryById(entity);
                    } else {
                        record = new Knowledge();
                        record.setContent("");
                        record.setTitle("");
                    }
                }
            } else {
                record = new Knowledge();
                record.setContent("");
                record.setTitle("");
            }
            result.put("result", record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 非登录加载树
     */
    @RequestMapping(value = "/publicTreelist", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> publicTreelist(@JsonParam Knowledge entity, HttpSession session,
                                        HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Knowledge root = new Knowledge();
            // long corpId = entity.getLoginCorpId();
            root.setText("root");
            List<Knowledge> list = null;
            if (entity.getShareId() == null) {
                list = knowledgeService.queryRoot(entity);
            } else {
                Knowledge shareEntity = knowledgeService.queryRootByShareId(entity);
                list = new ArrayList<Knowledge>();
                list.add(shareEntity);
            }

            root.setChildren(list);
            // knowledgeService.queryTreeByRoot(root, "Y", corpId);
            result.put("success", true);
            result.put("tree", true);
            //传根节点
            result.put("list", root);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("list", new Orgnization());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 加载树
     */
    @RequestMapping(value = "/treelist", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> treelist(@JsonParam QueryParams qps,@JsonParam Knowledge entity, HttpSession session,
                                        HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Knowledge root = new Knowledge();
            root.setText("root");
            CoreUser user = UserUtil.getUser();
            entity.setLoginCorpId(user.getCorpid());
            List<Knowledge> list = null;
            if (entity.getShareId() == null) {
                list = knowledgeService.queryRoot(new Knowledge());
            } else {
                Knowledge shareEntity = knowledgeService.queryRootByShareId(entity);
                list = new ArrayList<Knowledge>();
                list.add(shareEntity);
            }
            // long corpId = entity.getLoginCorpId();

            root.setChildren(list);
            // knowledgeService.queryTreeByRoot(root, "N", corpId);
            result.put("success", true);
            result.put("tree", true);
            //传根节点
            result.put("list", root);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("list", new Orgnization());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 根据条件查询记录,默认分页(若将'pageFlag'设置为'false'，则不分页)
     */
    @Override
    @RequestMapping(value = "/queryByExamplePage")
    @ResponseBody
    public Map<String, Object> queryByExamplePage(@JsonParam QueryParams qps, @JsonParam Knowledge entity, HttpSession session,
                                                  HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        LinkRedisClient jedis = RedisUtil.getJedis();
        CoreUser user = UserUtil.getUser();
        try {
            qps.addSorter(new Sorter("created", Sorter.DIR_DESC));
            Knowledge t = (Knowledge) BasicModel.transformClass(entity, qps);
            List<Knowledge> list = knowledgeService.queryByExamplePage(t);
            // 获取点赞量、浏览量等等缓存数据
            for (Knowledge item: list) {
                knowledgeService.setStatisticsData(item, user == null ? null : user.getId());
            }
            result.put("success", true);
            result.put("rows", list);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            result.put("total", getCount((BasicModel) t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<Knowledge>());
            result.put("result", e.getMessage());
        } finally {
            RedisUtil.returnResource(jedis);
        }
        return result;
    }

    /**
     * 根据条件查询记录,未登录时使用，添加publicTag==’Y'条件
     */
    @RequestMapping(value = "/publicQueryByExamplePage")
    @ResponseBody
    public Map<String, Object> publicQueryByExamplePage(@JsonParam QueryParams qps, @JsonParam Knowledge entity, HttpSession session,
                                                  HttpServletRequest request, HttpServletResponse response) {
        entity.setPublicTag("Y");
        return queryByExamplePage(qps, entity, session, request, response);
    }

    @RequestMapping(value = "/queryByNode")
    @ResponseBody
    public Map<String, Object> queryByNode(@JsonParam QueryParams qps,@JsonParam Knowledge entity, HttpSession session,
                                           HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            qps.setSort("F_TRANS_PINYIN_CAPITAL(title)");
            qps.setOrder("asc");
            Knowledge t = (Knowledge) BasicModel.transformClass(entity.getClass(), qps);
            t.setSecondaryType(entity.getSecondaryType());
            t.setPageFlag(false);
            List<Knowledge> list = knowledgeService.queryLeafByNode(t);
            int i = 0;
            for (Knowledge knowledge : list) {
                i++;
                knowledge.setSerial(entity.getSerial() + "." + i + " ");
            }
            t.setChildren(list);
            result.put("success", true);
            result.put("list", t);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<Knowledge>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/publicQueryByNode")
    @ResponseBody
    public Map<String, Object> publicQueryByNode(@JsonParam QueryParams qps,@JsonParam Knowledge entity, HttpSession session,
                                           HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            qps.setSort("F_TRANS_PINYIN_CAPITAL(title)");
            qps.setOrder("asc");
            Knowledge t = (Knowledge) BasicModel.transformClass(entity.getClass(), qps);
            t.setSecondaryType(entity.getSecondaryType());
            t.setPageFlag(false);
            List<Knowledge> list = knowledgeService.queryLeafByNode(t);
            List<Knowledge> results = new ArrayList<>();
            for (Knowledge temp : list) {
                if (temp.getPublicTag().equals("Y")) {
                    results.add(temp);
                }
            }
            int i = 0;
            for (Knowledge knowledge : results) {
                i++;
                knowledge.setSerial(entity.getSerial() + "." + i + " ");
            }
            t.setChildren(results);
            result.put("success", true);
            result.put("list", t);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<Knowledge>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>浏览量加一</p>
     *
     * @author 何启谦
     */
    @RequestMapping(value = "/increasePageviews")
    @ResponseBody
    public Map<String, Object> insert(@JsonParam Knowledge entity) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer pageviews = knowledgeService.increasePageviews(entity.getId());
            result.put("pageviews", pageviews);
            result.put("success", true);
        } catch (BasicServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getDetailMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>浏览量加一</p>
     *
     * @author 何启谦
     */
    @RequestMapping(value = "/increasePV/{id}")
    @ResponseBody
    public Map<String, Object> increasePV(@PathVariable(value = "id", required = true) Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer pv = knowledgeService.increasePV(id);
            result.put("pv", pv);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 移动端-营销助手-查询知识库文章各类型总数
     *
     * @author lizt
     * 2017年4月11日
     */
    @RequestMapping(value = "/queryKnowledgeTypeNum", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Map<String, Object> queryKnowledgeTypeNum(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        Knowledge record = new Knowledge();
        try {
            List<Knowledge> list = knowledgeService.queryKnowledgeTypeNum(record);
            result.put("success", true);
            result.put("result", list);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.toString());
        }
        return result;
    }

    /**
     * 移动端-经销商平台-查询知识库文章各类型总数
     *
     * @author Tipor
     */
    @RequestMapping(value = "/queryAppKnowledgeTypeNum", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Map<String, Object> queryAppKnowledgeTypeNum(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        Knowledge record = new Knowledge();
        try {
            List<Knowledge> list = knowledgeService.queryAppKnowledgeTypeNum(record);
            result.put("success", true);
            result.put("result", list);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.toString());
        }
        return result;
    }

    /**
     * 获取历史版本
     *
     * @author tangjian
     * @date 2018/11/19
     */
    @RequestMapping(value = "/queryKnowledgeById", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryKnowledgeById(@JsonParam Knowledge k, HttpSession session,
                                                  HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Knowledge record = knowledgeService.queryById(k);
            knowledgeService.setStatisticsData(record, null);
            record.setAnonymousFlag("Y");
            result.put("result", record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.toString());
        }
        return result;
    }

    /**
     * 模糊查询
     *
     * @author 朱泊阳
     * @date 2019/5/23
     */
    @RequestMapping(value = "/queryKnowledgeByExamplePage", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryKnowledgeByExamplePage(@JsonParam Knowledge k, HttpSession session,
                                                  HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            List<Knowledge> list = knowledgeService.queryKnowledgeByExamplePage(k);
            result.put("total", getCount(k, list.size()));
            result.put("rows", list);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", "查询失败");
        }
        return result;
    }

    /**
     * 模糊查询公开
     *
     * @author 朱泊阳
     * @date 2019/5/23
     */
    @RequestMapping(value = "/queryPublicKnowledgeByExamplePage", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryPublicKnowledgeByExamplePage(@JsonParam Knowledge k, HttpSession session,
                                                           HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            //设置为搜索公开知识库
            k.setAttr5("Y");
            List<Knowledge> list = knowledgeService.queryKnowledgeByExamplePage(k);
            result.put("total", getCount(k, list.size()));
            result.put("rows", list);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", "查询失败");
        }
        return result;
    }

    /**
     * 查询一条公开记录
     */
    @RequestMapping(value = "/queryPublicById")
    @ResponseBody
    public Map<String, Object> queryPublicById(@JsonParam Knowledge entity, HttpSession session,
                                         HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            entity.setAttr5("Y");
            Knowledge know = getBasicService().queryById(entity);
            if (know != null) {
                knowledgeService.setStatisticsData(know, null);
            } else {
                know = new Knowledge();
                know.setContent("");
                know.setTitle("");
                know.setPublicTag("N");
            }
            result.put("result", know);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }
}
